package ru.sstu.renju.players;

import java.util.Map;
import java.util.WeakHashMap;

import ru.sstu.renju.core.CellType;
import ru.sstu.renju.core.Game;
import ru.sstu.renju.core.Move;
import ru.sstu.renju.core.Player;

/**
 * {@code HumanPlayer} class represents {@link Player} doing moves when
 * human clicks mouse button.
 *
 * @author denis_murashev
 * @since Renju 1.0
 */
public class HumanPlayer implements Player {

	private Map<Game, Move> moves = new WeakHashMap<Game, Move>();

	@Override
	public String toString() {
		return "Human";
	}

	@Override
	public synchronized Move doMove(Game game, CellType type) {
		while (true) {
			try {
				wait();
			} catch (InterruptedException e) {
				System.err.println(e);
			}
			Move move = moves.get(game);
			if (move == null) {
				// Check if game is over and return from here
				return null;
			}
			if (game.isFreeCell(move.getX(), move.getY())) {
				return new Move(game, move.getX(), move.getY());
			}
		}
	}

	/**
	 * @param move the move
	 */
	public synchronized void setMove(Move move) {
		if (move != null) {
			moves.put(move.getGame(), move);
		}
		notify();
	}
}
